﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Runtime.Serialization;
using System.Web;
using SergeyPravodelov.Practice.BookStore.Data.Model;

namespace SergeyPravodelov.Practice.BookStore.Models
{
    [DataContract(Name = "book")]
    public class Book : Entity
    {
        internal static readonly byte[] _sDummy;
        internal static byte [] DefaultImage
        {
            get { return _sDummy; }
        }

        static Book()
        {
            var noImageFileName = HttpContext.Current.Server.MapPath("~/Content/app/resources/no_image.png");
            var buffer = new byte[16*1024];

            using (var fs = new FileStream(noImageFileName, FileMode.Open))
            {
                using (var ms = new MemoryStream())
                {
                    int read;
                    while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                    _sDummy = ms.ToArray();
                }
            }
        }
        
        [DataMember ( Name = "id" )]
        public override int Id { get; set; }

        [Required]
        [StringLength(30)]
        [DataMember(Name = "title")]
        public string Title { get; set; }

        [Range(0, 10000)]
        [DataMember ( Name = "pages" )]
        public int Pages { get; set; }

        [StringLength(30)]
        [DataMember ( Name = "publisher" )]
        public string Publisher { get; set; }

        [Required]
        [Range ( 1800 , int.MaxValue )]
        [DataMember ( Name = "year" )]
        public int Year { get; set; }

        public byte[] ImageBitmap { get; set; }

        [Required]
        [DataMember ( Name = "authors" )]
        public List<BookAuthor> Authors { get; set; }

        [RegularExpression ( @"^(?=.{17}$)97(?:8|9)([ -])\d{1,5}\1\d{1,7}\1\d{1,6}\1\d$" , ErrorMessage = "Invalid ISBN (Format: XXX-X-XX-XXXXXX-X)" )]
        [DataMember ( Name = "isbn" )]
        public string ISBN { get; set; }
    }
}